# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>
import logging
from excavator.utils.file import write
from excavator.utils.output import ExcavatorJobOutput
from excavator.job.base import Job
from excavator.models.report import notify_err, notify_info
from excavator.group import BootGroup
from excavator.models.pkg import DnfUpgrade
from excavator.models.openssh import OpenSshPermitRootLogin, default_openssh_permitrootlogin

logger = logging.getLogger("excavator.job")


class BootOpenssh(Job):
    group = BootGroup
    requires = (DnfUpgrade, OpenSshPermitRootLogin)
    provides = ()

    def run(self, *args, **kwargs):
        ExcavatorJobOutput.info(self.name, "restore ssh config")
        try:
            logger.info("get old ssh config")
            obj = OpenSshPermitRootLogin.get()
            if obj.value == default_openssh_permitrootlogin:
                notify_info("skip restore ssh config", self.name)
            else:
                logger.info("set PermitRootLogin as {}".format(obj.value))
                custom_config = "/etc/ssh/sshd_config.d/01-permitrootlogin.conf"
                body = "PermitRootLogin {}".format(obj.value)
                try:
                    write(custom_config, body)
                    notify_info("set PermitRootLogin success", self.name)
                except Exception as e:
                    logger.error(e)
                    notify_err(e, self.name)
        except Exception as e:
            logger.error(e)
            notify_err(e, self.name)
